Recursion: Using the same computation repeatedly until a problem is solved.
Recursive Method: A method that calls itself
// Sum of first n integers
public static long sum(int n)
{
if(n==1)
return 1;
else
return n + sum(n-1);
}
Java implements methods using an internal stack of activation records, where each record provides a snapshot of a method’s state during its execution.
Example: Although it seems
sum()
is just calling itself, it’s actually calling clones of itself.
Some mathematical problems are designed to be solved recursively.
public static int fib(int n)
{
if (n==0) { return 0;}
if (n==1) { return 1;}
return fib(n-1) + fib(n-2);
}
S(0)=0
and S(1)=1
Iterative solution:
public static int fib(int n)
{
int cur = 1, prev = 0;
int temp;
for (int i = 2; i <= n; i++){
= cur;
temp = prev + cur;
cur = temp;
prev }
return cur;
}
A problem can be solved with recursion if it can be broken into successive smaller problems that are identical to the overall problem.
Overhead is when recursive solutions repetitively:
Note: Overhead does not occur with a loop.
Way Recursion Works:
Infinite Recursion: When a recursive method doesn’t check/misses the base case or doesn’t get simpler, executing “forever”
public static int binarySearch(int[] nums, int target){
return binarySearchHelper(nums, 0, nums.length-1, target);
}
public static int binarySearchHelper(int[] nums, int start, int end, int target){
if (end < start)
return -1;
int m = (start+end)/2;
if (nums[m] == target)
return m;
else if (nums[m] < target)
return binarySearchHelper(nums, mid+1, end, target);
else
return binarySearchHelper(nums,start,mid-1,target);
}